#include"Mutex.hpp"
#include"thread.hpp"
#include<unistd.h>

int tickets = 1000;

pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;

void* getTicket(void* args)
{
    std::string name = static_cast<const char*>(args);
    while(true)
    {
        {
            LockGuard lockguard(&lock);
            pthread_cond_wait(&cond,&lock);
            if (tickets > 0)
            {
                usleep(1234);
                std::cout << name << " 正在进行抢票: " << tickets << std::endl;
                tickets--;
            }
            else
            {
                break;
            }
        }
    }

    return nullptr;
}

int main()
{

    pthread_t t1,t2,t3,t4;
    pthread_create(&t1,nullptr,getTicket,(void*)"thread 1");
    pthread_create(&t2,nullptr,getTicket,(void*)"thread 2");
    pthread_create(&t3,nullptr,getTicket,(void*)"thread 3");
    pthread_create(&t4,nullptr,getTicket,(void*)"thread 4");

    while(true)
    {
        usleep(1234);
        pthread_cond_signal(&cond);
        //pthread_cond_broadcast(&cond);
        //std::cout<<"give pthread a signal "<<std::cout;
        if(tickets==0) break;
    }

    pthread_join(t1,nullptr);
    pthread_join(t2,nullptr);
    pthread_join(t3,nullptr);
    pthread_join(t4,nullptr);
    return 0;
}